# Dreams have to come true after all
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from Financial.resource.transaction.serializer import DealRecordPaginateSerializer
from comment import db

from comment.models.deal_log import Deal_log
from comment.models.debt_info import Debt_info
from comment.models.loanApply import Loan
from comment.models.User import User


class Deal_record(Resource):

    def get(self):
        rp = RequestParser()
        rp.add_argument('start')  # 开始时间
        rp.add_argument('end')  # 结束时间
        rp.add_argument('deal_type')  # 交易类型
        rp.add_argument('curPage')  # 当前页
        rp.add_argument('perPage')  # 每页数量

        args = rp.parse_args()

        start = args.get('start')
        end = args.get('end')
        deal_type = int(args.get('deal_type'))
        curPage = int(args.get('curPage'))
        perPage = int(args.get('perPage'))

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        logList = Deal_log.query
        if deal_type > 0:
            logList = Deal_log.query.filter(Deal_log.aType == deal_type)

        if not user.role:
            logList = logList.filter(Deal_log.aUserId == user_id)

        if start and end:
            logList = logList.filter(db.cast(Deal_log.aDate, db.DATE) >= db.cast(start, db.DATE)).filter(
                db.cast(Deal_log.aDate, db.DATE) <= db.cast(end, db.DATE)).paginate(curPage, perPage, error_out=False)
        else:
            logList = logList.paginate(curPage, perPage, error_out=False)

        data = DealRecordPaginateSerializer(logList).to_dict()

        return {'msg': 'success', 'data': data}